package org.cocos2dx.javascript.Mob;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SMSBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("SMSBroadcastReceiver", "android.provider.Telephony.SMS_RECEIVED");
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            SmsMessage[] messages = getMessageFromIntent(intent);
            for(SmsMessage msg: messages){

                String strMsg = msg.getDisplayMessageBody();
                Log.e("SMSBroadcastReceiver", strMsg);
                Pattern p = Pattern.compile("\\d{6}");
                Matcher m = p.matcher(strMsg);
                String verifyCode = null;
                while(m.find()){
                    verifyCode = m.group();
                    break;
                }

                if (mSMSListener != null){
                    mSMSListener.onSmsReceiver(verifyCode);
                }
            }
        }
    }

    private static ISMSListener mSMSListener;

    private SmsMessage[] getMessageFromIntent(Intent intent){
        Object[] messages = (Object[])intent.getSerializableExtra("pdus");
        byte[][] pduObjes = new byte[messages.length][];
        for(int i = 0; i < messages.length; i++){
            pduObjes[i] = ((byte[])messages[i]);
        }

        byte[][] pdus = new byte[pduObjes.length][];
        int pduCount = pdus.length;
        SmsMessage[] msg = new SmsMessage[pduCount];
        for(int i = 0; i < pduCount; i++){
            pdus[i] = pduObjes[i];
            msg[i] = SmsMessage.createFromPdu(pdus[i]);
        }

        return msg;
    }

    public interface ISMSListener{
        void onSmsReceiver(String verifyCode);
    }

    public SMSBroadcastReceiver(ISMSListener mSmsListener){
        super();
        this.mSMSListener = mSmsListener;
    }
}
